package com.dlwx.parttimetalent.weibo;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.Toast;

import com.dlwx.parttimetalent.R;
import com.dlwx.parttimetalent.bean.WeiboUser;
import com.dlwx.parttimetalent.comm.Constant;
import com.dlwx.parttimetalent.utils.ToastUtils;
import com.dlwx.parttimetalent.wxapi.CallBackListenerUtiles;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.auth.AccessTokenKeeper;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WbConnectErrorMessage;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.sina.weibo.sdk.utils.Utility;

/**
 * Created by Administrator on 2017/12/22.
 */

public class WeiboUitls {
    private Activity context;
    /** 注意：SsoHandler 仅当 SDK 支持 SSO 时有效 */
    private SsoHandler mSsoHandler;
    /** 封装了 "access_token"，"expires_in"，"refresh_token"，并提供了他们的管理功能  */
    private Oauth2AccessToken mAccessToken;
    private WbShareHandler shareHandler;
    private String shareUrl;

    public WeiboUitls(Activity context) {
        this.context = context;
        mSsoHandler = new SsoHandler(context);
        mAccessToken = AccessTokenKeeper.readAccessToken(context);
    }
    public void login(){
        mSsoHandler.authorize(new SelfWbAuthListener());
        
    }
    public SsoHandler getSso(){
        return  mSsoHandler;
    }

    private class SelfWbAuthListener implements com.sina.weibo.sdk.auth.WbAuthListener{
        @Override
        public void onSuccess(final Oauth2AccessToken token) {
            mAccessToken = token;
            if (mAccessToken.isSessionValid()) {
                getWeiboUserInfo(token);
                AccessTokenKeeper.writeAccessToken(context, mAccessToken);
//                Toast.makeText(context, "认证成功", Toast.LENGTH_SHORT).show();
            }
//            context.runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//
//                }
//            });
        }

        @Override
        public void cancel() {
//            Toast.makeText(context, "认证取消", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onFailure(WbConnectErrorMessage errorMessage) {
            Toast.makeText(context, errorMessage.getErrorMessage(), Toast.LENGTH_LONG).show();
        }
    }

    public  void share(String url){
        shareUrl=url;
        shareHandler = new WbShareHandler(context);
        shareHandler.registerApp();
        sendMultiMessage(true,true);
    }
    /**
     * 第三方应用发送请求消息到微博，唤起微博分享界面。
     */
    private void sendMultiMessage(boolean hasText, boolean hasImage) {
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
//        weiboMessage.mediaObject=getWebpageObj();
        if (hasText) {
            weiboMessage.textObject = getTextObj();
        }
        if (hasImage) {
            weiboMessage.imageObject = getImageObj();
        }
        shareHandler.shareMessage(weiboMessage, false);


    }
    /**
     * 创建多媒体（网页）消息对象。
     *
     * @return 多媒体（网页）消息对象。
     */
    private WebpageObject getWebpageObj() {
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title =Constant.SHARE_TITLE;
        mediaObject.description =  Constant.SHARE_CONTENT;
        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.logo_share);
        // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
        mediaObject.setThumbImage(bitmap);
        mediaObject.actionUrl = shareUrl;
//        mediaObject.actionUrl = shareUrl;
        mediaObject.defaultText = "Webpage 默认文案";
        return mediaObject;
    }

    /**
     * 获取分享的文本模板。
     */
    private String getSharedText() {
       String  text = Constant.SHARE_CONTENT+" #约神#"+shareUrl;
       return text;
    }

    /**
     * 创建文本消息对象。
     * @return 文本消息对象。
     */
    private TextObject getTextObj() {
        TextObject textObject = new TextObject();
        textObject.text = getSharedText();
        textObject.title = Constant.SHARE_TITLE;
        textObject.actionUrl = shareUrl;
        return textObject;
    }
    /**
     *
     * 创建图片消息对象。
     * @return 图片消息对象。
     */
    private ImageObject getImageObj() {
        ImageObject imageObject = new ImageObject();
        Bitmap  bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.logo_weibo_share);
        imageObject.setImageObject(bitmap);
        return imageObject;
    }


    private void getWeiboUserInfo(Oauth2AccessToken token) {
        OkGo.<String>get("https://api.weibo.com/2/users/show.json")
                .params("access_token",token.getToken())
                .params("uid",token.getUid())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if(response==null){return;}
                        String res=response.body().toString();
                        WeiboUser bean= new Gson().fromJson(res, WeiboUser.class);
                        if(bean==null){return;};
                        if (CallBackListenerUtiles.callBackListener != null) {
                            CallBackListenerUtiles.callBackListener.getUserInfo(bean.getName(),bean.getProfile_image_url(),bean.getId(),"", Constant.WEIBO);
                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.toastForShort(context,context.getString(R.string.bad_net));
                    }
                });
    }
}
